package com.keon.jianbao.ui.activity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.AppUpdate;
import com.keon.jianbao.bean.Appraisal;
import com.keon.jianbao.bean.DetailAppraisal;
import com.keon.jianbao.bean.Expert;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.enu.AppraisalStatus;
import com.keon.jianbao.enu.WebType;
import com.keon.jianbao.ui.widget.ItemLayout;
import com.keon.jianbao.util.CommonUtils;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;
import com.keon.jianbao.util.TDevice;
import com.keon.jianbao.util.WechatUtils;

import org.apache.http.Header;
import org.json.JSONException;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.DefaultSliderView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by keon on 2015/9/29.
 */
public class AppraisalDetailActivity extends BaseActivity {

    String downLoadUrl = "";

    private PopupWindow mPopupwinow = null;
    View popupView = null;

    int appraisalId = 0;
    DetailAppraisal detailAppraisal = null;

    @Bind(R.id.appraisal_detail_indicator)
    InfiniteIndicatorLayout iilIndicator;
    @Bind(R.id.appraisal_detail_appraisal_expert)
    ItemLayout llExpert;
    @Bind(R.id.appraisal_detail_appraisal_expert_result)
    ItemLayout llExpertResult;
    @Bind(R.id.appraisal_detail_appraisal_name)
    ItemLayout llName;
    @Bind(R.id.appraisal_detail_appraisal_catlog)
    ItemLayout llCatlog;
    @Bind(R.id.appraisal_detail_appraisal_age)
    ItemLayout llAge;
    @Bind(R.id.appraisal_detail_appraisal_size)
    ItemLayout llSize;
    @Bind(R.id.appraisal_detail_appraisal_expert_result_text)
    ItemLayout llResultText;
    @Bind(R.id.appraisal_detail_desc)
    ItemLayout llDesc;
    @Bind(R.id.appraisal_detail_back_reason)
    ItemLayout llBackReason;
    @Bind(R.id.appraisal_detail_back_remark)
    ItemLayout llBackRemark;
    @Bind(R.id.appraisal_detail_expert_comment_layout)
    LinearLayout llCommentLayout;
    @Bind(R.id.appraisal_detail_expert_comment)
    TextView tvExpertComment;
    @Bind(R.id.appraisal_desc_star)
    ItemLayout ilStar;
    @Bind(R.id.appraisal_ll_pay)
    LinearLayout llPay;
    @Bind(R.id.appraisal_pay)
    TextView tvPay;
    @Bind(R.id.appraisal_cancel)
    TextView tvCancel;
    @Bind(R.id.appraisal_ll_expert_comment)
    LinearLayout llExpertComment;

    PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            showToast("分享一下");
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            showToast("系统或网络错误");
        }

        @Override
        public void onCancel(Platform platform, int i) {
            showToast("取消操作");
        }
    };

    SimpleHandler appraisalDetailHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);

            try {
                Result result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    detailAppraisal = JsonUtils.fromJson(result.getContent(), DetailAppraisal.class);
                    if (detailAppraisal.getStatus() == AppraisalStatus.APPRAISALED.getStatus()) {
                        appraisaledInit(detailAppraisal);
                    } else if (detailAppraisal.getStatus() == AppraisalStatus.BACK.getStatus()) {
                        backInit(detailAppraisal);
                    } else if (detailAppraisal.getStatus() == AppraisalStatus.APPRAISAL.getStatus()) {
                        AppraisalInit(detailAppraisal);
                    } else if (detailAppraisal.getStatus() == AppraisalStatus.UNPAID.getStatus()) {
                        unpayInit(detailAppraisal);
                    }

                    if (detailAppraisal.getStar() == 0) {
                        ilStar.setVisibility(View.GONE);
                    } else {
                        ilStar.setVisibility(View.VISIBLE);
                        ilStar.setTitle(R.string.expert_comment_text);
                        ilStar.setText(getString(detailAppraisal.getStar2()));
                        ilStar.setSummary(detailAppraisal.getComment());
                    }

                } else {
                    onBackPressed();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };

    SimpleHandler updateHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);

            try {
                Result result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    AppUpdate appUpdate = JsonUtils.fromJson(result.getContent(), AppUpdate.class);
                    downLoadUrl = appUpdate.getDownload();

                } else {
                    onBackPressed();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_appraisal_detail;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.appraisal_detail;
    }

    @Override
    public void initView() {
        appraisalDetailHandler.setContext(this);
        updateHandler.setContext(this);
        llDesc.setOnClickListener(this);
        tvExpertComment.setOnClickListener(this);

        initPopup();
    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getExtras();
        appraisalId = bundle.getInt("id");

        showWaitDialog();
        Api.appraisal_detail(appraisalId, appraisalDetailHandler);
        Api.apk_update(updateHandler);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.appraisal_detail_desc:
                if (detailAppraisal != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("detailAppraisal", detailAppraisal);
                    jump(AppraisalDescActivity.class, bundle);
                } else {
                    showToast(R.string.common_error_network);
                    onBackPressed();
                }

                break;
            case R.id.appraisal_detail_expert_comment:
                if (detailAppraisal.getStar() == 0) {
                    Bundle bundle = new Bundle();
//                Expert expert = new Expert(detailAppraisal.getExpert_id(), detailAppraisal.getExpert_appraisal_name(), "", "接口无此字段", detailAppraisal.getExpert_appraisal_time(), 0, detailAppraisal.getExpert_fee());
                    bundle.putInt("expert_id", detailAppraisal.getExpert_id());
                    bundle.putInt("appraisalId", appraisalId);
                    bundle.putSerializable("detailAppraisal", detailAppraisal);
                    jump(ExpertCommentActivity.class, bundle);
                } else {
                    showToast("该鉴宝已评价");
                }

                break;
            case R.id.share_wechat:

                CommonUtils.share(this, "漏漏客户端", downLoadUrl, null, WechatMoments.NAME, platformActionListener);
                mPopupwinow.dismiss();
                break;
            case R.id.share_qq:
//                showToast("2");
                CommonUtils.share(this, "漏漏客户端", downLoadUrl, null, QQ.NAME, platformActionListener);
                mPopupwinow.dismiss();
                break;
            case R.id.share_weibo:
                CommonUtils.share(this, "漏漏客户端", downLoadUrl, null, SinaWeibo.NAME, platformActionListener);
//                CommonUtils.share(this, url, null, SinaWeibo.NAME, platformActionListener);
                mPopupwinow.dismiss();
                break;

        }
    }

    private void appraisaledInit(DetailAppraisal detailAppraisal) {
        initIndicator(detailAppraisal.getAppraisal_image());
        llExpert.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());
        llExpertResult.setTitle(StringUtils.getColorString(detailAppraisal.getExpert_appraisal_result(), R.string.appraisal_detail_appraisal_expert_result, detailAppraisal.getExpert_appraisal_result(), R.color.assistTextColor));
        llName.setTitle(R.string.appraisal_detail_appraisal_name, detailAppraisal.getAppraisal_name());
        llCatlog.setTitle(R.string.appraisal_detail_appraisal_catlog, detailAppraisal.getAppraisal_catalog());
        llAge.setTitle(R.string.appraisal_detail_appraisal_age, detailAppraisal.getAppraisal_age());
        llSize.setTitle(R.string.appraisal_detail_appraisal_size, detailAppraisal.getAppraisal_size());
        llResultText.setTitle(R.string.appraisal_detail_appraisal_expert_result, detailAppraisal.getExpert_appraisal_detail());
        llDesc.setTitle(R.string.appraisal_detail_desc);
        llBackReason.setVisibility(View.GONE);
        llBackRemark.setVisibility(View.GONE);
    }

    private void backInit(DetailAppraisal detailAppraisal) {
        initIndicator(detailAppraisal.getAppraisal_image());
        llExpert.setTitle(R.string.appraisal_detail_owner, detailAppraisal.getUser_name());
        llExpertResult.setTitle(R.string.appraisal_detail_create_time, detailAppraisal.getCreate_time());
        llName.setTitle(R.string.appraisal_detail_appraisal_name, detailAppraisal.getAppraisal_name());
        llCatlog.setTitle(R.string.appraisal_detail_appraisal_catlog, detailAppraisal.getAppraisal_catalog());
        llAge.setTitle(R.string.appraisal_detail_appraisal_age, detailAppraisal.getAppraisal_age());
        llSize.setTitle(R.string.appraisal_detail_appraisal_size, detailAppraisal.getAppraisal_size());
        llResultText.setTitle(R.string.appraisal_detail_desc2, detailAppraisal.getAppraisal_desc());
        llDesc.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());
        String reason = "";
        ArrayList<String> reasons = detailAppraisal.getExpert_refuse_reason();
        for (int i = 0; i < reasons.size(); i++) {
            reason += (reasons.get(i) + "|");
        }
        reason = reason.substring(0, reason.length() - 1);
        llBackReason.setTitle(R.string.appraisal_detail_back_reason, reason);
        llBackRemark.setTitle(R.string.appraisal_detail_back_remark, detailAppraisal.getExpert_refuse_detail());
        llCommentLayout.setVisibility(View.GONE);
    }

    private void AppraisalInit(DetailAppraisal detailAppraisal) {
        initIndicator(detailAppraisal.getAppraisal_image());
        llExpert.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());
        llExpertResult.setTitle(R.string.appraisal_detail_expert_status, detailAppraisal.getStatus_alias());
        llName.setTitle(R.string.appraisal_detail_appraisal_name, detailAppraisal.getAppraisal_name());
        llCatlog.setTitle(R.string.appraisal_detail_appraisal_catlog, detailAppraisal.getAppraisal_catalog());
        llAge.setTitle(R.string.appraisal_detail_appraisal_age, detailAppraisal.getAppraisal_age());
        llSize.setTitle(R.string.appraisal_detail_appraisal_size, detailAppraisal.getAppraisal_size());
        llResultText.setTitle(R.string.appraisal_detail_desc2, detailAppraisal.getAppraisal_desc());
        llDesc.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());
        llExpertComment.setVisibility(View.GONE);
        llBackReason.setVisibility(View.GONE);
        llBackRemark.setVisibility(View.GONE);
        llCommentLayout.setVisibility(View.GONE);
    }

    private void unpayInit(final DetailAppraisal detailAppraisal) {
        initIndicator(detailAppraisal.getAppraisal_image());
        llExpert.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());
//        llExpertResult.setTitle(R.string.appraisal_detail_status, detailAppraisal.getStatus_alias());
//        String str = String.format(getResources().getString(R.string.appraisal_detail_status), detailAppraisal.getStatus_alias());
//
//        SpannableString ss = new SpannableString(str);
//        ss.setSpan(new ForegroundColorSpan(AppContext.getResource().getColor(R.color.assistTextColor)), 4, detailAppraisal.getStatus_alias().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        llExpertResult.setTitle(ss);

        llExpertResult.setTitle(StringUtils.getColorString(detailAppraisal.getStatus_alias(), R.string.appraisal_detail_status, detailAppraisal.getStatus_alias(), R.color.assistTextColor));

        llName.setTitle(R.string.appraisal_detail_appraisal_name, detailAppraisal.getAppraisal_name());
        llCatlog.setTitle(R.string.appraisal_detail_appraisal_catlog, detailAppraisal.getAppraisal_catalog());
        llAge.setTitle(R.string.appraisal_detail_appraisal_age, detailAppraisal.getAppraisal_age());
        llSize.setTitle(R.string.appraisal_detail_appraisal_size, detailAppraisal.getAppraisal_size());
        llResultText.setTitle(R.string.appraisal_detail_desc2, detailAppraisal.getAppraisal_desc());
        llDesc.setTitle(R.string.appraisal_detail_appraisal_expert, detailAppraisal.getExpert_name());

        llBackReason.setVisibility(View.GONE);
        llBackRemark.setVisibility(View.GONE);
        llExpertComment.setVisibility(View.GONE);
        llPay.setVisibility(View.VISIBLE);
        tvPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("appraisal_id", detailAppraisal.getId());
                AppraisalDetailActivity.this.jump(JianBaoPayWayActivity.class, bundle);
            }
        });
    }

    private void initIndicator(ArrayList<String> imgs) {
        HashMap<String, String> url_maps = new HashMap<String, String>();
        url_maps = new HashMap<String, String>();
        for (int i = 0; i < imgs.size(); i++) {
            url_maps.put(i + "", imgs.get(i).toString());
        }

        for (String name : url_maps.keySet()) {
            DefaultSliderView textSliderView = new DefaultSliderView(this);
            textSliderView
                    .image(url_maps.get(name))
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .showImageResForEmpty(R.mipmap.page_icon_empty)
                    .showImageResForError(R.mipmap.page_icon_network);
            textSliderView.getBundle()
                    .putString("extra", name);
            iilIndicator.addSlider(textSliderView);
        }
        iilIndicator.setScrollDurationFactor(0.7);
        iilIndicator.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
        iilIndicator.startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        iilIndicator.stopAutoScroll();
    }

    @Override
    public void onResume() {
        super.onResume();
        iilIndicator.startAutoScroll();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        return super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_share, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.item_share:
                mPopupwinow.showAsDropDown(toolbar, TDevice.getDisplayMetrics().widthPixels - 52, 0);
                break;
        }
        return true;
    }

    void initPopup() {
        if (mPopupwinow == null) {
            popupView = LayoutInflater.from(this).inflate(
                    R.layout.view_share, null);
            mPopupwinow = new PopupWindow(popupView,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT, true);
            mPopupwinow.setBackgroundDrawable(new ColorDrawable(
                    0x00000000));

            popupView.findViewById(R.id.share_wechat).setOnClickListener(this);
            popupView.findViewById(R.id.share_qq).setOnClickListener(this);
            popupView.findViewById(R.id.share_weibo).setOnClickListener(this);
        }
    }
}
